package com.controller;

import com.constant.Constant;
import com.entity.GoldPoints;
import com.entity.User;
import com.exception.ServiceException;
import com.service.GoldPointService;
import com.service.UserService;
import com.util.AjaxResult;
import com.util.CommonUtil;
import org.aspectj.weaver.loadtime.Aj;
import com.util.DateUtil;
import com.vo.ChapterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.entity.User;
import com.github.pagehelper.PageInfo;
import com.service.UserService;
import com.util.AjaxResult;
import com.vo.UserBackVo;
import org.apache.ibatis.javassist.bytecode.stackmap.BasicBlock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import sun.applet.resources.MsgAppletViewer;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Controller
@RequestMapping("/user")
public class UserCtl {
    @Autowired
    UserService userService;
    @Autowired
    GoldPointService goldPointService;

    @RequestMapping("/loginBack.do")
    @ResponseBody
//    后台管理员登陆 pj
    public AjaxResult loginBack(User user1, String code, HttpServletRequest request){
        AjaxResult result=new AjaxResult(true,"注册成功",null);
        String localCode= (String) request.getSession().getAttribute("code");
        if(localCode==null || !localCode.equals("code")){
            result.setMsg("验证码错误");
            result.setSuccess(false);
        }
        User user=userService.findUserAdmin(user1);
        try {
            if ("admin".equals(user.getRole())) {
                if (user.getPassword().equals(user1.getPassword())) {
                    result.setSuccess(true);
                } else {
                    result.setMsg("密码错误");
                }
            } else {
                result.setMsg("您不是管理员！");
                result.setSuccess(false);
            }
        }catch (Exception e){
            result.setMsg("请重新输入");
        }

        return result;

    }

//    根据条件分页查询用户   pj

    @RequestMapping("/findBackUser.do")
    @ResponseBody
    public PageInfo<User> findBackUser(@RequestParam("pageNo") String pageNo, UserBackVo userBackVo){
//              AjaxResult result=new AjaxResult(true,"查询成功",null);
              PageInfo<User> info = userService.findBackUser(pageNo, userBackVo);
              return info;
    }

//    后台修改用户信息 pj

    @RequestMapping("modifyBackUser.do")
    @ResponseBody
    public AjaxResult modifyBackUser(User user){

        AjaxResult result=new AjaxResult(true, "修改成功",null);
        userService.modifyBackUser(user);
        return result;
    }

//    后台显示用户信息 pj
    @RequestMapping("/showBackUser.do")
    @ResponseBody
    public AjaxResult showBackUser(Integer id){
//        AjaxResult result=new AjaxResult(true,"",null);
        System.out.println("----------------id"+id);
        AjaxResult result1 = userService.showBackUser(id);
        return result1;
    }








    @RequestMapping("/regist.do")
    @ResponseBody
//    注册
    public AjaxResult regist(User user){
        System.out.println("sssssss"+user);
        try {
            userService.regist(user);
            return AjaxResult.isOk();
        }catch (ServiceException e){
            return AjaxResult.isFail(e.getMessage());
        }

    }
    @RequestMapping("/check.do")
    @ResponseBody
//    杨跃森
//    检查用户名
    public AjaxResult checkloginName(@RequestParam("login_name") String loginName){
        String rep="^[A-Za-z0-9]+$";
        if (!loginName.matches(rep)){
            return AjaxResult.isFail("用户名只能下划线，字母，数字组成");
        }else {
            return AjaxResult.isOk();
        }
    }
    @RequestMapping("/checkEmail")
    @ResponseBody
//    杨跃森
//    检查邮箱
    public AjaxResult checkEmail(String email){
        System.out.println("emailTest");
        String rep="^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\\.[a-zA-Z0-9_-]{2,3}){1,2})$";
        if (!email.matches(rep)){
            return AjaxResult.isFail("请输入正确的邮箱格式1212121");
        }
        try {
            userService.findByEmail(email);
            return AjaxResult.isOk();
        }catch (ServiceException e){
            return AjaxResult.isFail(e.getMessage());

        }
    }
    @RequestMapping("/modifyUser.do")
    @ResponseBody
//    杨跃森
//    修改用户信息
    public AjaxResult modifyUser(User u, HttpServletRequest request){
        try {
            AjaxResult ajaxResult = new AjaxResult();
            u.setStatus(0);
            String newPassword = request.getParameter("newPassword");
            u.setPassword(newPassword);
            int i = userService.updateUser(u);
            User id = userService.findById(u.getId());
            if(i==1&&id!=null){
                request.getSession().setAttribute(Constant.SESSION_USER,id);
            }
            return AjaxResult.isOk("修改成功");
        }catch (ServiceException se){
            se.printStackTrace();
            return AjaxResult.isFail(se.getMessage());
        }



    }
    @RequestMapping("/loginFront.do")
    @ResponseBody
//    杨跃森
//    登录
    public AjaxResult login(HttpServletRequest request,String login_name, String password, HttpSession session){
        System.out.println(login_name);
        AjaxResult ar = userService.findUser(login_name, password);
        User user = (User) ar.getObj();
        System.out.println("User="+user);
        if (ar.getSuccess()==true){
            request.getSession().setAttribute(Constant.SESSION_USER,user);
            System.out.println("已经创建session");
        }else {
            throw new ServiceException("登录失败");
        }
        return ar;
    }
//    杨跃森
//    退出登录
    @RequestMapping("/loginOut1.do")
    public String  loginOut1(HttpServletRequest request){
        request.getSession().invalidate();
        return "/front/front_index";
    }
//    杨跃森
//    签到更新时间
    @RequestMapping("/updateLoginDate.do")
    @ResponseBody
    public AjaxResult updateLoginDate(HttpServletRequest request, User user, HttpServletResponse response){
        int user_id = user.getId();
        GoldPoints goldPoints = new GoldPoints(user.getId(),5,0,"签到获得5积分",new Date());
        Date date = goldPointService.findPointGold(user.getId());
        if (date==null){
            int i = goldPointService.AddPointGold(goldPoints);
            return AjaxResult.isOk();
        }else {
            boolean needSign = DateUtil.isNeedSign(date);
            if (needSign==true){
                goldPointService.AddPointGold(goldPoints);
            }
        }
        return AjaxResult.isFail("签到失败");
    }
//    杨跃森
//    判断是否需要签到
//    有问题
    @RequestMapping("/findLoginDate.do")
    @ResponseBody
    public boolean findLoginDate(HttpSession session){

        User user = (User) session.getAttribute(Constant.SESSION_USER);
        System.out.println("获取上次签到的时间"+user);
        Date date = goldPointService.findPointGold(user.getId());
        System.out.println("2eddddddddddddddddddddddddddd"+date);


        boolean isNeedSign = false;
        System.out.println("===============================================");
        if(date== null){
            isNeedSign =true;
        }else {
            isNeedSign = DateUtil.isNeedSign(date );
        }
        System.out.println("是否需要签到"+isNeedSign);
        return  isNeedSign ;

    }

    @RequestMapping("/getCode.do")
    public void getCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("UserController.getCode()");
        CommonUtil.MyImage m = CommonUtil.getImage(null, 4, true, true);
        System.out.println("code=" + m.getCode());
        request.getSession().setAttribute("code", m.getCode());
        ServletOutputStream responseOutputStream = response.getOutputStream();
        // 输出图象到页面
        ImageIO.write(m.getImage(), "JPEG", responseOutputStream);
        // 以下关闭输入流！
        responseOutputStream.flush();
        responseOutputStream.close();
    }
}
